
// simple example of a java app for mysql
// read input, parse, decide what to do
//
// be sure the MySQL JDBC driver is in your CLASSPATH
//
// user will see prompt >
// user can type "search title x" or "search author x" to search by title or author
// user can type "select n" to select item number n from the search results
// user can type "review r text" to review item number n, giving it rating r (on a scale of 1 to 5) and review text "text"

import java.io.*;
import java.sql.*;

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;


/**
 * TODO:
 * -parse .dat files
 * -connect to mysql db
 */

///// load data local infile 'customers.dat' into table customers;
///// create table customers(custid char(15), last varchar(20), first varchar(20), primary key(custId));
/**
 * what about customer addresses?
 */
///// create table reviews(asin varchar(10), custid varchar(15), rating integer, entered date, reviewText text, primary key(asin, custid));



//d
public class CustomerApp {
	
	DatabaseHelper db;
	
	Connection cn;

	// currentResults holds current results from a search() so that other methods can access them
	ResultSet currentResults;

	// currentItem holds the row number of an itme the user is looking at (so we can use currentResults.absolute(currentItem) to go to it
	String currentItem;

	public CustomerApp(String dbname, String userid, String password) throws SQLException {
		cn = null;
		currentResults = null;
		currentItem = null;
		
		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/"+dbname, userid, password);
		} catch (Exception e) {
			System.out.println("connection failed: " + e);
		}
		
		db = new DatabaseHelper(cn, currentResults, currentItem);
		
		// read in the data from the local .dat files

	}

	public static void main (String[] args) throws JSchException, IOException, InterruptedException, SQLException {
		
		//get console to read from
		Console console;
		console = System.console();
		/**
		 * I set this up myself, when I installed my personal Mysql Server 
		 */
		String dbname = "db";
		String userid = "root";
		String password = "toor";

		
		CustomerApp app = new CustomerApp(dbname, userid, password);
		/*
		app.db.dropAllTables();
		app.db.init();
		app.db.executeUpdate("load data infile 'Customers.dat' into table Customers");
		app.db.executeUpdate("load data infile 'products.dat' into table Books");
		app.db.executeUpdate("load data infile 'reviews.dat' into table Reviews");
		
		*/
		

		
		
		//app.db.displayCustomers();
		//app.db.displayOrders();
		//app.db.displayBooks();
		
		//app.db.create_table_customers();
		//app.db.create_table_books();
		//app.db.create_table_reviews();
		//app.db.create_table_orders();
		
		//app.db.displayBooks();
		//app.db.searchBooksBy("title", "ben stiller");

		
		// for input from stdin
		String line = "";
		InputStreamReader instream = new InputStreamReader(System.in);
		BufferedReader in = new BufferedReader(instream);
		
		System.out.println("init to create database tables: (* RUN ONCE *)");
		System.out.println("search [author|title|...] x to search.");
		System.out.println("select n to select one of the search results.");
		System.out.println("review r text to review your selection.");
		System.out.println("quit to quit.");
		// loop while waiting for input
		while (!(line.equals("quit"))) {
			System.out.print("> ");

			try {
				line = in.readLine();
			} catch (Exception e) {
				System.out.println("error: " + e);
			}
			
			// tokenize
			String[] tokens = line.toLowerCase().split("\\s");

			
			// first token is command
			if(tokens[0].equals("order")){
				app.order();
			}
			if (tokens[0].equals("search"))
				app.search(tokens);
			else if (tokens[0].equals("select"))
				app.selectBook(tokens[1]);
			else if (tokens[0].equals("review"))
				app.review(tokens);
			else if (tokens[0].equals("quit"))
				;	
			else if (tokens[0].equals("init"))
			    app.db.init();
			else
				System.out.println("don't understand request.");
		}

	}

	// search by title or author (or other things)
	void search(String[] tokens) throws SQLException {
		
		String full_name = new String();
		for(int i = 2; i < tokens.length; i++){
			full_name = full_name + " " + tokens[i];
		}
		full_name = full_name.substring(1);
		// check tokens[1] for search type
		if (tokens[1].equals("title")) {
			// plug title into a prepared SQL query
			this.currentResults = this.db.searchBooksBy("title", full_name);
		}
		else if (tokens[1].equals("author")) {
			// plug author into a prepared SQL query
			this.currentResults = this.db.searchBooksBy("author", full_name);
		}
		// etc
		else {
			System.out.println("don't understand search request.");
			return;
		}

		// execute query
		// currentResults = ...

		// display results
	}

	// select an item from current search results (if any)
	void select(String[] tokens) throws SQLException {
		String select_this = tokens[1];
		String full_name = getFullName(tokens);
		if(currentResults == null){
			//nothing to select from
			System.out.printf("No search results to select from! performa search.");
		}
		else{
			//select the given item from results
			System.out.println(currentResults.getRow());
			int count = 1;
			while(currentResults.next() && count <= Integer.parseInt(tokens[1])){
				count++;
			}
			currentItem = currentResults.getString("asin");
			
		}	
		
		fetchSelectedItem();
		
		return;
		}

		// got to handle errors.  make sure tokens[1] can be converted to an integer and that it's not bigger than the number of current results.
		// currentItem = Integer.parseInt(tokens[1]);

		// currentResults.absolute(...)
		// display info about selected item
	

	// review the current selected item
	void review(String[] tokens) {
		if (currentItem == null) {
			System.out.println("do a search first!");
			return;
		}
		else{
			
		}

		// convert tokens to rating and review text, update database
	}
	
	
	/**
	 * place an order, insert into orders.
	 * get all necessary information (address/name from customer etc)
	 * 
	 * @param tokens
	 * @throws IOException 
	 */
	void order() throws IOException{

		if(currentItem != null){

			System.out.println("no item select!");
			System.out.println("use select <row> after searching for books");
		}
		if(currentItem.length() <= 4){
			System.out.println("fuck");
		}
	
		
		
	        InputStreamReader isr = new InputStreamReader(System.in);
	        BufferedReader br = new BufferedReader(isr);
	        String s = br.readLine();
	 

		
	}
	
	/**
	 * concatenates the remaining tokens[] parameters to form the full title or author's name.
	 * @param tokens 
	 * @return a string containing the full title or author name
	 */
	String getFullName(String[] tokens){
		
		String full_name = new String();
		for(int i = 2; i < tokens.length; i++){
			full_name = full_name + " " + tokens[i];
		}
		
		if(full_name.length() > 1) full_name = full_name.substring(1);
		return full_name;
		
	}
	
	
	/**
	 * returns the currently selected entry from the books database
	 * @throws SQLException
	 */
	void fetchSelectedItem() throws SQLException{
		
		this.currentResults = this.db.executeQuery("SELECT * FROM Books");
		this.currentResults = db.rs;
		while(currentResults.next()){
			if(currentResults.getString("asin").equals(currentItem)) break;
			
		
		}
		System.out.println("found at " + currentResults.getRow());
	}
	
	
	public void selectBook(String srow) throws SQLException{
		String ssrow = new String(srow);
		int row = Integer.parseInt(ssrow);
		System.out.println("about to select order at row " + row);
		//this.currentResults = this.db.rs;
		int i = 1;

		while(currentResults.next()){
			System.out.println(currentResults.getRow());
			if(i == row){
				this.currentItem = currentResults.getString("asin");
				System.out.println("found at row " + currentItem);
				
			}
			i++;
		}
		
	}
	
	
}
